package com.powernode.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.anno.Log;
import com.powernode.domain.SysRole;
import com.powernode.service.SysRoleService;
import com.powernode.vo.RoleAndMenu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "角色接口管理")
@RequestMapping("/sys/role")
@RestController
public class RoleController {
    @Autowired
    private SysRoleService sysRoleService;

    @ApiOperation("查询系统角色集合")
    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('sys:role:list')")
    public ResponseEntity<List<SysRole>> loadSysRoleList() {
        List<SysRole> roleList = sysRoleService.list();
        return ResponseEntity.ok(roleList);
    }


    @ApiOperation("分页查询用户角色")
    @GetMapping("/page")
    public ResponseEntity<Page<SysRole>> loadSysRolePageList(Page<SysRole> page, SysRole sysRole) {

        sysRoleService.page(page, new LambdaQueryWrapper<SysRole>()
                .like(sysRole != null && StrUtil.isNotBlank(sysRole.getRoleName()), SysRole::getRoleName, sysRole.getRoleName())
                .orderByDesc(SysRole::getCreateTime)
                );
        return ResponseEntity.ok(page);
    }

    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:role:save')")
    @Log(operation = "新增角色和响应权限")
    public ResponseEntity<Void> save(@RequestBody RoleAndMenu roleAndMenu) {
        sysRoleService.saveRoleAndMenu(roleAndMenu);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("查看角色和权限")
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:role:info')")
    public ResponseEntity<RoleAndMenu> loadRoleAndMenu(@PathVariable("id") Long rid) {
        RoleAndMenu roleAndMenu = sysRoleService.selectRoleAndMenuById(rid);
        return ResponseEntity.ok(roleAndMenu);
    }

    @ApiOperation("删除角色和响应的权限")
    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('sys:role:delete')")
    @Log(operation = "删除角色和响应权限")
    public ResponseEntity<Void> deleteRoleAndMenu(@RequestBody List<Long> roleIdList) {
        sysRoleService.deleteRoleAndMenu(roleIdList);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("修改角色和其权限信息")
    @PutMapping
    @PreAuthorize("hasAnyAuthority('sys:role:update')")
    @Log(operation = "修改角色和响应权限")
    public ResponseEntity<Void> modifyRoleAndMenu(@RequestBody RoleAndMenu roleAndMenu) {
        sysRoleService.modifyRoleAndMenu(roleAndMenu);
        return ResponseEntity.ok().build();
    }
}


